package com.mszlu.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mszlu.blog.common.Result;
import com.mszlu.blog.common.SysUserThreadLocal;
import com.mszlu.blog.dao.ArticleDAO;
import com.mszlu.blog.entity.*;
import com.mszlu.blog.entity.dto.Archive;
import com.mszlu.blog.entity.dto.ArticleDto;
import com.mszlu.blog.entity.request.ArticlePage;
import com.mszlu.blog.service.*;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleDAO, Article> implements ArticleService {

    @Autowired
    private ArticleDAO articleDAO;

    @Autowired
    private SysUserServive sysUserServive;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleBodyService articleBodyService;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private TagService tagService;

    @Autowired
    private ThreadPoolService threadPoolService;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public Result listArchives() {
        Map<String, Integer> map = new HashMap<>();

        List<Article> allArticles = this.list();

        for (Article x : allArticles) {

            LocalDateTime date = LocalDateTime.ofEpochSecond(x.getCreateDate()/1000, 0, ZoneOffset.ofHours(8));

            int yearo = date.getYear();

            int montho = date.getMonth().getValue();

            String key1 = yearo+"/"+montho;

            if (map.get(key1) != null){
                map.put(key1,map.get(key1) + 1);
            }else {
                map.put(key1, 1);
            }
        }

        List<Archive> list = new ArrayList<>();

        for(Map.Entry entry : map.entrySet()){
            String mapKey = (String) entry.getKey();
            int count = (int) entry.getValue();

            int year = Integer.parseInt(mapKey.split("/")[0]);
            int month = Integer.parseInt(mapKey.split("/")[1]);

            Archive archive = new Archive(year,month,count);

            list.add(archive);
        }

        return Result.success(list);
    }




    @Override
    public Result newArticles() {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.orderByDesc(Article::getCreateDate);

        Page<Article> page = new Page<>(1,5);

        this.page(page,lambdaQueryWrapper);

        return Result.success(page.getRecords());
    }

    @Override
    public Result hot() {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Article::getViewCounts);

        Page<Article> page = new Page<>(1,5);

        this.page(page,lambdaQueryWrapper);

        return Result.success(page.getRecords());
    }

    @Override
    public Result viewsById(Long id) {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(Article::getId,id);

        Article one = this.getOne(lambdaQueryWrapper);

        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(one,articleDto);

        SysUser author = sysUserServive.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getId,one.getAuthorId()));
        Category category = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getId,one.getCategoryId()));
        ArticleBody body = articleBodyService.getOne(new LambdaQueryWrapper<ArticleBody>().eq(ArticleBody::getId,one.getBodyId()));

        List<ArticleTag> articleTags = articleTagService.list(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getArticleId,one.getId()));
        List<Long> tagsId = new ArrayList<>();
        for (ArticleTag x :articleTags) {
            tagsId.add(x.getTagId());
        }

        LambdaQueryWrapper<Tag> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.in(Tag::getId,tagsId);
        List<Tag> tags = tagService.list(lambdaQueryWrapper1);

        articleDto.setAuthor(author.getNickname());
        articleDto.setBody(body);
        articleDto.setCategory(category);
        articleDto.setTags(tags);

        //更新    阅读数
        threadPoolService.updateViewCounts(one);

        return Result.success(articleDto);
    }

    @Override
    public Result pulish(ArticleDto articleDto) {

        Article article = articleDto;
        ArticleBody articleBody = articleDto.getBody();
        List<Tag> tags = articleDto.getTags();

        SysUser author = SysUserThreadLocal.get();
        article.setAuthorId(author.getId());
        article.setWeight(0);
        articleDAO.insert(article);

        List<ArticleTag> articleTags = new ArrayList<>();
        for (Tag x : tags) {
            ArticleTag articleTag = new ArticleTag();
            articleTag.setTagId(x.getId());
            articleTag.setArticleId(article.getId());
            articleTags.add(articleTag);
        }
        articleTagService.saveBatch(articleTags);

        articleBody.setArticleId(article.getId());
        articleBodyService.save(articleBody);

        article.setBodyId(articleBody.getId());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setViewCounts(0);
        article.setCategoryId(articleDto.getCategory().getId());

        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Article::getId,article.getId());

        articleDAO.update(article,lambdaQueryWrapper);

        //--------------------------------------
        //插入es
        //1.准备request对象
        IndexRequest request = new IndexRequest("articles").id(article.getId().toString());
        //2.编写request对象
        request.source(JSON.toJSONString(article),XContentType.JSON);
        //3.发送请求
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //--------------------------------------

        return Result.success(article);
    }

    @Override
    public Result<List> getPage(ArticlePage articlePage) {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<Article> page = new Page<>(articlePage.getPage(),articlePage.getPageSize());

        if (articlePage.getYear() == null && articlePage.getMonth() == null) {

            lambdaQueryWrapper.orderByDesc(articlePage.getSort().equals("desc") && articlePage.getName().equals("a.createDate"),
                    Article::getCreateDate);
        }else {

            LocalDateTime localDateTime1 = LocalDateTime.of(articlePage.getYear(),articlePage.getMonth(),1,0,0,0);
            Instant instant1 = localDateTime1.toInstant(ZoneOffset.UTC);
            long date1 = instant1.toEpochMilli();

            LocalDateTime localDateTime2 = LocalDateTime.of(articlePage.getYear(),articlePage.getMonth()+1,1,0,0,0);
            Instant instant2 = localDateTime2.toInstant(ZoneOffset.UTC);
            long date2 = instant2.toEpochMilli();

            lambdaQueryWrapper.between(Article::getCreateDate,date1,date2);
            lambdaQueryWrapper.orderByDesc(articlePage.getSort().equals("desc") && articlePage.getName().equals("a.createDate"),
                    Article::getCreateDate);

        }

        if (articlePage.getTagId() != null) {
            LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(ArticleTag::getTagId,articlePage.getTagId());
            List<ArticleTag> articleTags = articleTagService.list(lambdaQueryWrapper1);
            List<Long> articleIds = new ArrayList<>();
            for (ArticleTag x : articleTags) {
                articleIds.add(x.getArticleId());
            }
            lambdaQueryWrapper.in(Article::getId,articleIds);
        }

        this.page(page,lambdaQueryWrapper);
        return Result.success(page.getRecords());
    }

    @Override
    public Result getPage2(ArticlePage articlePage) {
        //创建request对象
        SearchRequest request = new SearchRequest("articles");

        //分页
        Integer page = articlePage.getPage();
        Integer size = articlePage.getPageSize();
        request.source().from( (page - 1) * size).size(size);

        // 构建booleanQuery
        buildBasicQuery(articlePage, request);

        // 3. 发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 4. 处理响应
        Page<Article> articleESPage = handleResponse(response);

        return Result.success(articleESPage.getRecords());
    }

    private Page<Article> handleResponse(SearchResponse response) {

        //解析response
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        //        System.out.println("共搜索到 " + total + " 条数据");

        SearchHit[] hits = searchHits.getHits();
        List<Article> articles = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Article article = JSON.parseObject(json, Article.class);
            //获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //根据字段名获取高亮结果
            if (!CollectionUtils.isEmpty(highlightFields)){

                HighlightField highlightField3 = highlightFields.get("summary");
                if (highlightField3 != null){
                    //获取高亮值
                    String string = highlightField3.getFragments()[0].string();
                    //覆盖非高亮结果
                    article.setSummary(string);
                }

                HighlightField highlightField4 = highlightFields.get("title");
                if (highlightField4 != null){
                    //获取高亮值
                    String string = highlightField4.getFragments()[0].string();
                    //覆盖非高亮结果
                    article.setTitle(string);
                }

            }
            //-------------------------------
            articles.add(article);
        }
        Page<Article> page = new Page<>();
        log.info("查询到 {} 条数据",total);
        page.setTotal(total).setRecords(articles);
        return page;
    }

    private void buildBasicQuery(ArticlePage articlePage, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (articlePage.getYear() != null && articlePage.getMonth() != null) {

            LocalDateTime localDateTime1 = LocalDateTime.of(articlePage.getYear(),articlePage.getMonth(),1,0,0,0);
            Instant instant1 = localDateTime1.toInstant(ZoneOffset.UTC);
            long date1 = instant1.toEpochMilli();

            LocalDateTime localDateTime2 = LocalDateTime.of(articlePage.getYear(),articlePage.getMonth()+1,1,0,0,0);
            Instant instant2 = localDateTime2.toInstant(ZoneOffset.UTC);
            long date2 = instant2.toEpochMilli();

            boolQuery.filter(QueryBuilders.rangeQuery("createDate").gte(date1).lte(date2));

        }

        if (articlePage.getSort().equals("desc") && articlePage.getName().equals("a.createDate")){
            request.source().sort(SortBuilders.fieldSort("createDate").order(SortOrder.DESC));
        }

        //categoryId
        if (articlePage.getCategoryId()!=null){
            boolQuery.filter(QueryBuilders.matchQuery("categoryId",articlePage.getCategoryId()));
        }

        if (articlePage.getTagId() != null){
            LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(ArticleTag::getTagId,articlePage.getTagId());
            List<ArticleTag> articleTags = articleTagService.list(lambdaQueryWrapper1);
            List<Long> articleIds = new ArrayList<>();
            for (ArticleTag x : articleTags) {
                articleIds.add(x.getArticleId());
            }
            boolQuery.filter(QueryBuilders.termsQuery("id",articleIds));
        }

        HighlightBuilder highlightBuilder = null;
        if (!StringUtils.isEmpty(articlePage.getKeyWord())){
            boolQuery.must(QueryBuilders.matchQuery("all", articlePage.getKeyWord()));

            highlightBuilder = new HighlightBuilder();
            highlightBuilder.requireFieldMatch(false)//因为高亮查询默认是对查询字段即description就行高亮，可以关闭字段匹配，这样就可以对查询到的多个字段（前提是有关键词并且改字段可以分词）进行高亮显示
                    .field("summary")
                    .field("title");
        }

        if (highlightBuilder == null){
            request.source().query(boolQuery);
        }else {
            request.source().query(boolQuery).highlighter(highlightBuilder);
        }

    }
}
